package cn.wowjoy.office.common.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import java.util.HashMap;
import java.util.List;

import cn.wowjoy.office.R;


/**
 * Created by 84429 on 2017/4/1.
 */

public class GridViewApdapter extends BaseAdapter {
    private LayoutInflater mInflater;
    private Context context;
    private List<String> list;
    private HashMap<Integer, String> tempList;

    public GridViewApdapter(Context context, List<String> data) {
        mInflater = LayoutInflater.from(context);
        this.context = context;
        this.list = data;
        tempList = new HashMap<>();
    }

    @Override
    public int getCount() {
        return null == list ? 0 : list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public String getSelectedMed() {
        StringBuffer sb = new StringBuffer();
        for (Integer key : tempList.keySet()) {
            sb.append(tempList.get(key));
            sb.append(",");
        }
        return sb.toString();
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.item_checkbox, null);
            holder.mTV = (TextView) convertView.findViewById(R.id.name);
            holder.mCB = (CheckBox) convertView.findViewById(R.id.check);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.mTV.setText(list.get(position));

        holder.mCB.setOnCheckedChangeListener(null);
        if (tempList.get(position) == null)
            holder.mCB.setChecked(false);
        else
            holder.mCB.setChecked(true);
        holder.mCB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked)
                    tempList.put(position, list.get(position));
                else
                    tempList.remove(position);
            }
        });

        return convertView;
    }

    class ViewHolder {
        CheckBox mCB;
        TextView mTV;
    }
}
